package com.qf.deviceconsumeropenfeign9003.interceptors;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

/**
 * @author ghy
 * @version 1.0
 * @date 2022-01-18
 **/
//@Component
public class CookieInterceptor implements RequestInterceptor {

    /**
     * 在调用feign接口[testCookie]之前进行拦截，对其进行请求数据补充
     * @param template
     */
    @Override
    public void apply(RequestTemplate template) {

        String tokenStr = "";

        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        Cookie[] cookies = request.getCookies();
        if(!ObjectUtils.isEmpty(cookies)) {
            for (Cookie cookie : cookies) {
                //login_token=aaa1223
                if("login_token".equals(cookie.getName())) {
                    tokenStr = "token=" + cookie.getValue();
                    continue;
                }
            }
        }
        //token的值，应该是服务消费者传递过来的login_token
        template.header(HttpHeaders.COOKIE, tokenStr);
    }
}
